import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
import matplotlib as mpl
import matplotlib.font_manager as fm

# 尝试注册工作区里的中文字体以便 matplotlib 正确渲染中文
font_path = "/Users/somi/machine/Hiragino Sans GB.ttc"
myfont = None
if os.path.exists(font_path):
    try:
        fm.fontManager.addfont(font_path)
        mpl.rcParams['font.family'] = 'Hiragino Sans GB'
        mpl.rcParams['axes.unicode_minus'] = False  # 让负号正常显示
        # 也创建一个 FontProperties 实例，便于单独在标题/文本中使用
        myfont = fm.FontProperties(fname=font_path)
    except Exception:
        # 如果注册字体失败，继续运行但会有中文渲染警告
        print(f"警告：无法注册字体 {font_path}")
else:
    print(f"警告：字体文件未找到：{font_path}")

# 1. 读取桌面的 logi-y.txt 文件
file_path = "/Users/somi/machine/002/logi-y.txt"
df = pd.read_csv(
    file_path, 
    header=None,
    names=["x", "y", "label"],
    sep=","
)

# 2. 绘制散点图（保存到桌面）
plt.figure(figsize=(10, 6))
sns.set_style("whitegrid")

for label, color, legend_name in [(0, "lightblue", "Label=0"), (1, "coral", "Label=1")]:
    data_subset = df[df["label"] == label]
    plt.scatter(
        x=data_subset["x"], 
        y=data_subset["y"], 
        c=color, 
        label=legend_name, 
        alpha=0.7,
        s=60,
        edgecolors="black", 
        linewidth=0.5
    )

plt.xlabel("X Value", fontsize=12, fontweight="bold")
plt.ylabel("Y Value", fontsize=12, fontweight="bold")
plt.title("散点图：X 与 Y（按标签分组）", fontsize=14, fontweight="bold", fontproperties=myfont)
plt.legend(fontsize=10)
plt.grid(True, alpha=0.3)

# 直接显示散点图而不是保存到桌面
plt.show()

# 3. 绘制箱形图（保存到桌面）
fig, (ax_x, ax_y) = plt.subplots(2, 1, figsize=(10, 10), sharex=True)
sns.set_style("whitegrid")

# 子图1：x变量的箱形图
sns.boxplot(
    x="label", 
    y="x", 
    data=df, 
    ax=ax_x, 
    palette=["lightblue", "coral"],
    boxprops=dict(color="black"),
    medianprops=dict(color="black", linewidth=2),
    whiskerprops=dict(color="black"),
    capprops=dict(color="black")
)
ax_x.set_ylabel("X Value", fontsize=12, fontweight="bold")
ax_x.set_title("箱形图：X 值（按标签分组）", fontsize=13, fontweight="bold", fontproperties=myfont)
ax_x.grid(True, alpha=0.3, axis="y")

# 子图2：y变量的箱形图
sns.boxplot(
    x="label", 
    y="y", 
    data=df, 
    ax=ax_y, 
    palette=["lightblue", "coral"],
    boxprops=dict(color="black"),
    medianprops=dict(color="black", linewidth=2),
    whiskerprops=dict(color="black"),
    capprops=dict(color="black")
)
ax_y.set_xlabel("Label (0 / 1)", fontsize=12, fontweight="bold")
ax_y.set_ylabel("Y Value", fontsize=12, fontweight="bold")
ax_y.set_title("箱形图：Y 值（按标签分组）", fontsize=13, fontweight="bold", fontproperties=myfont)
ax_y.grid(True, alpha=0.3, axis="y")

plt.tight_layout()
# 直接显示箱形图而不是保存到桌面
plt.show()

print("图表已显示（如果运行在有图形界面的环境中，会弹出窗口）")